<template>
  <div>
    <el-form :model="ruleForm" ref="form">
      <el-form-item label="用户名" prop="username" :rules="rules">
        <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="add">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
//   beforeRouteEnter(to, from, next) {
//     //可以请求ajax数据,没有this
//     next(vm => {
//       //这种方式拿vue实例
//       console.log(vm);
//     });
//   },
  beforeRouteLeave(to, from, next) {
    if (this.ruleForm.username && !this.flag) {
      this.$confirm("是否提交?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          next();
        })
        .catch(() => {});
    }else{
        next();
    }
  },
  data() {
    return {
      flag: false,
      ruleForm: { username: "" },
      rules: [{ trigger: "blur", message: "请输入用户名" }]
    };
  },
  methods: {
    add() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.flag = true;
          //是否跟设置的规则相匹配
          let id = Math.random();
          let lists = JSON.parse(localStorage.getItem("lists")) || [];
          lists.push({ id, username: this.ruleForm.username });
          localStorage.setItem("lists", JSON.stringify(lists));
          this.$router.push("/user/list");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>